//
//  FriendApplyVerifyViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/4/13.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "FriendApplyVerifyViewController.h"
#import "NewingFriendModel.h"
#import "NewFriendTableViewCell.h"
#import "FriendSetViewController.h"
#import "ZGWNewingFriendModel.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface FriendApplyVerifyViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NewingFriendModel *friendApplyModel;
@property (nonatomic, strong) NSMutableArray *newingFriendApplyArray;
@property (nonatomic, strong) UITableView *friendApplyTableView;

@property (nonatomic, strong) NSTimer *myTimer; // 检查请求是否超时
@property (nonatomic, assign) NSInteger numberOfTime; // 存储请求时间

@property (nonatomic, strong) NSMutableArray *fenZuNameArray; // 分组名字数组
@property (nonatomic, strong) NSMutableDictionary *fenZuNameDuiYingArray; // 分组名字对应的IDDic


@end

@implementation FriendApplyVerifyViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
    [self.myTimer invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    
   
    // 请求网络并且添加数据

    [self checkNetAndAddData];
}


// navi的修改
- (void)changeNavigation
{
    self.navigationItem.title = @"好友验证";
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
 
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 请求网络并且添加数据
- (void)checkNetAndAddData
{
    if ([[[NetStatusHandle shareHandle] getNetStatus] isEqualToString:@"YES"]) {
        [self addData];
        // 建立计数器
        self.myTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(goTimeOnAddFriend:) userInfo:nil repeats:YES];
        self.numberOfTime = 0;
        [[NSRunLoop currentRunLoop] addTimer:self.myTimer forMode:NSRunLoopCommonModes];
        // 开启加载动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
    } else {
        NSLog(@"没有网络");
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kNoNetNoRefresh ToView:self];
    }
}

#pragma mark - 计时器
- (void)goTimeOnAddFriend:(NSTimer *)timer
{
    self.numberOfTime++;
    NSLog(@"添加朋友页请求时间:%ld", self.numberOfTime);
    if (self.numberOfTime > kZGWQingQiuChaoShi) {
        NSLog(@"添加朋友页请求超时");
        self.numberOfTime = 0;
        [self.myTimer invalidate];
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kQingQiuChaoShiNoReFresh ToView:self];
    }
}

#pragma mark - 添加数据源
- (void)addData
{
    // 用户好友申请列表
    NSString *friendApplyLieBiaoUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWNewingFriendLieBiao, kCurrentUserToken];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:friendApplyLieBiaoUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        [self.myTimer invalidate];
        self.numberOfTime = 0;
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        if (!responseObject) {
            return;
        }
        NSLog(@"融云好友model = %@", self.friendDataModel);
        NSLog(@"本地好友dic = %@", self.benDiFriendData);
        if (self.benDiFriendData.count == 0) {
            NSLog(@"融云本地数据");
            // 说明是融云本地好友消息
            RCContactNotificationMessage *rcNM = (RCContactNotificationMessage *)self.friendDataModel.lastestMessage;
           
            NSArray *friend_ship_requestsArray = [responseObject valueForKey:@"friend_ship_requests"];
            // 建立数据
            self.newingFriendApplyArray = [NSMutableArray array];
            for (NSDictionary *tempDic in friend_ship_requestsArray) {
                if ([self.friendDataModel.senderUserId isEqualToString:[tempDic valueForKey:@"user_id"]]) {
                    ZGWNewingFriendModel *model = [[ZGWNewingFriendModel alloc] init];
                    [model setValuesForKeysWithDictionary:tempDic];
                    [self.newingFriendApplyArray addObject:model];
                }
            }
            
            // 当前用户的分组数据
            self.fenZuNameArray = [NSMutableArray array];
            self.fenZuNameDuiYingArray = [NSMutableDictionary dictionary];
            NSArray *friend_groupArray = [responseObject valueForKey:@"friend_group"];
            for (NSDictionary *groupDic in friend_groupArray) {
                [self.fenZuNameArray addObject:[groupDic valueForKey:@"name"]];
                [self.fenZuNameDuiYingArray setValue:[NSString stringWithFormat:@"%@",[groupDic valueForKey:@"id"]] forKey:[groupDic valueForKey:@"name"]];
            }
            
           
            
        } else {
            // 说明是自己创建的本地好友数据库
            NSLog(@"自己创建的本地数据库");
            
            // 发送者ID
            NSString *senderID = [[NetStatusHandle shareHandle] getCurrentLoginRongCloudUserIDDuiYingSenderIDByKey:[self.benDiFriendData valueForKey:@"senderID"]];
            
            NSArray *friend_ship_requestsArray = [responseObject valueForKey:@"friend_ship_requests"];
            // 建立数据
            self.newingFriendApplyArray = [NSMutableArray array];
            for (NSDictionary *tempDic in friend_ship_requestsArray) {
                if ([senderID isEqualToString:[tempDic valueForKey:@"id"]]) {
                    ZGWNewingFriendModel *model = [[ZGWNewingFriendModel alloc] init];
                    [model setValuesForKeysWithDictionary:tempDic];
                    [self.newingFriendApplyArray addObject:model];
                }
            }
           
            // 当前用户的分组数据
            self.fenZuNameArray = [NSMutableArray array];
            self.fenZuNameDuiYingArray = [NSMutableDictionary dictionary];
            NSArray *friend_groupArray = [responseObject valueForKey:@"friend_group"];
            for (NSDictionary *groupDic in friend_groupArray) {
                [self.fenZuNameArray addObject:[groupDic valueForKey:@"name"]];
                [self.fenZuNameDuiYingArray setValue:[NSString stringWithFormat:@"%@",[groupDic valueForKey:@"id"]] forKey:[groupDic valueForKey:@"name"]];
            }
        }
        // 布局
        [self addMySubview];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self.myTimer invalidate];
        self.numberOfTime = 0;
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kHuoQuDataShiBaiNoRefresh ToView:self];
    }];
    
//    NSLog(@"融云好友model = %@", self.friendDataModel);
//    NSLog(@"本地好友dic = %@", self.benDiFriendData);
//    if (self.benDiFriendData.count == 0) {
//        NSLog(@"融云本地数据");
//        // 说明是融云本地好友消息
//        RCContactNotificationMessage *rcNM = (RCContactNotificationMessage *)self.friendDataModel.lastestMessage;
//        NSString *friendMessage = rcNM.message;
//        NSString *remarkString = [NSString stringWithFormat:@""];
//        // 获取发送者姓名
//        NSString *senderName = rcNM.extra;
//                if ([friendMessage isEqualToString:[NSString stringWithFormat:@"我是%@", senderName]]) {
//            remarkString = [NSString stringWithFormat:@"我是%@，我想加你为好友", senderName];
//        } else {
//            // 说明发送者附加信息了
//            remarkString = friendMessage;
//        }
//        
//        NSDictionary *tempDic = [NSDictionary dictionaryWithObjectsAndKeys:senderName, @"_name", remarkString, @"_mark", @"NO", @"_isHaveAgree", nil];
//        // 建立模拟数据
//        self.friendApplyModel = [[NewingFriendModel alloc] init];
//        [self.friendApplyModel setValuesForKeysWithDictionary:tempDic];
//    } else {
//        // 说明是自己创建的本地好友数据库
//        NSLog(@"自己创建的本地数据库");
//        // 发送者姓名
//        NSString *senderName = @"";
//        // remark
//        NSString *remarkString = @"";
//        // 消息内容
//        NSString *friendMessage = [self.benDiFriendData valueForKey:@"kSenderAddMessage"];
//        // 发送者ID
//        NSString *senderID = [[NetStatusHandle shareHandle] getCurrentLoginRongCloudUserIDDuiYingSenderIDByKey:[self.benDiFriendData valueForKey:@"senderID"]];
//        // 进行模拟数据的组件
//        if ([senderID isEqualToString:@"10000"]) {
//            senderName = @"张国文";
//        } else if ([senderID isEqualToString:@"10001"]) {
//            senderName = @"梅江林";
//        } else if ([senderID isEqualToString:@"10002"]) {
//            senderName = @"殷雄";
//        } else if ([senderID isEqualToString:@"10003"]) {
//            senderName = @"吕峰";
//        } else if ([senderID isEqualToString:@"10004"]) {
//            senderName = @"欧兆";
//        } else if ([senderID isEqualToString:@"10005"]) {
//            senderName = @"沈佳";
//        }
//        if ([friendMessage isEqualToString:@"haha"]) {
//            remarkString = [NSString stringWithFormat:@"我是%@，我想加你为好友", senderName];
//        } else {
//            // 说明发送者附加信息了
//            remarkString = friendMessage;
//        }
//        NSDictionary *tempDic = [NSDictionary dictionaryWithObjectsAndKeys:senderName, @"_name", remarkString, @"_mark", @"NO", @"_isHaveAgree", nil];
//        // 建立模拟数据
//        self.friendApplyModel = [[NewingFriendModel alloc] init];
//        [self.friendApplyModel setValuesForKeysWithDictionary:tempDic];
//    }
//
   
    
}

#pragma mark - 布局
- (void)addMySubview
{
    self.friendApplyTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    self.friendApplyTableView.dataSource = self;
    self.friendApplyTableView.delegate = self;
    self.friendApplyTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_friendApplyTableView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.newingFriendApplyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"applyFriend";
    NewFriendTableViewCell *cell = [[NewFriendTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.newingFriendApplyArray.count > indexPath.row) {
          cell.zgwNewingFriendModel = self.newingFriendApplyArray[indexPath.row];
    }
  
    [cell.agreeOrIngoreButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

#pragma mark - 好友申请点击同意
- (void)click:(UIButton *)button
{
    NSLog(@"好友申请同意");
    FriendSetViewController *friendSetVC = [[FriendSetViewController alloc] init];
    if (self.newingFriendApplyArray.count > 0) {
        ZGWNewingFriendModel *model = self.newingFriendApplyArray[0];
        friendSetVC.markName = model.nikename;
        friendSetVC.applyID = [NSString stringWithFormat:@"%@", model.applyID];
        friendSetVC.fenZuName = [NSMutableArray arrayWithArray:self.fenZuNameArray];
        friendSetVC.fenZuNameDuiYingDic = [NSMutableDictionary dictionaryWithDictionary:self.fenZuNameDuiYingArray];
        
        friendSetVC.zgwFriendSetVCBlock = ^void(NSString *string) {
            // 需要重新请求数据
            [self checkNetAndAddData];
        };
    }
    
    
    [self.navigationController pushViewController:friendSetVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 动态高度
    NewFriendTableViewCell *cell = (NewFriendTableViewCell *)[self tableView:self.friendApplyTableView cellForRowAtIndexPath:indexPath];
    return cell.liuYanLabel.bottom + 15 * kAdjustParamater;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
